<template>
  <div class="app-container">
    <div style="margin-bottom:10px">
      <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" style="display:inline-table;width:50%" />
      <div v-if="tableData && tableData.length>0" style="vertical-align:bottom;margin-left: 10px;width:50%;display:inline">
        <span>当前数据数： {{ tableData.length }}</span>
        <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="uploadAll">
          保存数据
        </el-button>
        <el-button class="filter-item" type="danger" icon="el-icon-plus" @click="resetData">
          重置
        </el-button>
      </div>
    </div>
    <el-table v-if="tableData && tableData.length>0" :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-popover
            v-if="!row.errMsg"
            :ref="row.id"
            placement="top"
            width="180"
          >
            <p>确定删除本条数据吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[row.id].doClose()">取消</el-button>
              <el-button type="primary" size="mini" @click="deleteRow(row)">确定</el-button>
            </div>
            <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini" />
          </el-popover>
          <br>
          <span v-if="row.errMsg" style="color:red">失败原因：{{ row.errMsg }}</span>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { uploadBatch } from '@/api/word/word'

export default {
  name: '导入单词',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: [],
      errArr: [],
      count: 0,
      syncLoading: false,
      label: { }
    }
  },
  methods: {
    uploadAll() {
      this.loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      if (this.tableData && this.tableData.length === 0) {
        return this.$message.error('请先选择数据')
      }
      // this.tableData.forEach((td, idx) => {
      //   this.submitForm(td)
      // })
      uploadBatch(this.tableData).then(response => {
        var errMsg = response.data
        var succIds = []
        this.tableData.forEach((td, idx) => {
          if (errMsg[td.id] === 'exists') {
            td.errMsg = '已存在'
          } else if (errMsg[td.id] === 'invalid_parameters') {
            td.errMsg = '信息缺失'
          } else if (errMsg[td.id]) {
            td.errMsg = '数据异常'
          } else {
            succIds.push(td.id)
          }
          if (idx === this.tableData.length - 1) {
            this.$message.success('数据上传成功，共' + this.tableData.length + '条数据，成功上传' +
              (this.tableData.length - Object.keys(errMsg).length) + '条数据，成功数据将自动从列表中移除')
            this.deleteRows(succIds)
            this.loading.close()
          }
        })
      }).catch(e => {
        this.loading.close()
        if (e === 'empty_data') {
          return this.$message.error('请先选择数据')
        } else {
          return this.$message.error('数据异常，导入失败')
        }
      })
    },
    resetData() {
      this.tableData = []
      this.header = []
    },
    beforeUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10
      if (isLt10M) {
        return true
      }
      this.$message({
        message: '暂不支持大于5M的文件',
        type: 'warning'
      })
      return false
    },
    handleSuccess({ results, header }) {
      results = results.filter((td, idx) => {
        td.id = idx
        td.name = td['单词']
        td.completePh = td['全面释义']
        td.simplePh = td['简明释义']
        td.prefix = td['前缀（prefix）']
        td.stem = td['词根（stem）']
        td.suffix = td['后缀（suffix）']
        td.note = td['单词笔记']
        td.disassembly = td['按照词根词缀隔开']
        return true
      })
      this.tableData = results
      // 处理头部
      header.unshift('id')
      this.tableHeader = header
    },
    deleteRow(row) {
      this.$refs[row.id].doClose()
      this.tableData.forEach((item, idx) => {
        if (item.id === row.id) {
          this.tableData.splice(idx, 1)
        }
      })
    },
    deleteRows(ids) {
      this.tableData = this.tableData.filter((item) => {
        return ids.indexOf(item.id) === -1
      })
    }
  }
}
</script>
